import _ from 'lodash';
import { Graph, Shape } from '@antv/x6';
import { EventItemType } from '../dict';
import { randomId } from '@/utils/utils';
import { WORK_RECT_NAME } from './shapes/WorkRect';
// import { VERIFY_DIAMOND_NAME } from './VerifyDiamond';
import { VERIFY_RECT_NAME } from './shapes/VerifyRect';
// import { END_CIRCLE_NAME } from './EndCircle';
import { START_RECT_NAME } from './shapes/StartRect';
import { END_RECT_NAME } from './shapes/EndRect';

import '@antv/x6-react-shape';
import ReactNode from './ReactNode';

const RectNodeDefault = () => ({
  shape: 'react-shape',
  component: 'react-node',
  id: randomId(),
  x: 40,
  y: 40,
  width: 172, // 默认宽度
  height: 40, // 默认高度
  data: {
    selected: false,
  },
  // 链接桩定义
  ports: {
    groups: {
      top: {
        position: 'top',
        label: {
          position: 'top',
        },
        attrs: {
          circle: {
            r: 4,
            magnet: true,
            stroke: '#31d0c6',
            strokeWidth: 2,
            fill: '#fff',
            style: {
              visibility: 'hidden',
            },
          },
        },
      },
      right: {
        position: 'right',
        label: {
          position: 'right',
        },
        attrs: {
          circle: {
            r: 4,
            magnet: true,
            stroke: '#31d0c6',
            strokeWidth: 2,
            fill: '#fff',
            style: {
              visibility: 'hidden',
            },
          },
        },
      },
      bottom: {
        position: 'bottom',
        label: {
          position: 'bottom',
        },
        attrs: {
          circle: {
            r: 4,
            magnet: true,
            stroke: '#31d0c6',
            strokeWidth: 2,
            fill: '#fff',
            style: {
              visibility: 'hidden',
            },
          },
        },
      },
      left: {
        position: 'left',
        label: {
          position: 'left',
        },
        attrs: {
          circle: {
            r: 4,
            magnet: true,
            stroke: '#31d0c6',
            strokeWidth: 2,
            fill: '#fff',
            style: {
              visibility: 'hidden',
            },
          },
        },
      },
    },
    items: [
      {
        id: 'port1',
        group: 'top',
      },
      {
        id: 'port2',
        group: 'right',
      },
      {
        id: 'port3',
        group: 'bottom',
      },
      {
        id: 'port4',
        group: 'left',
      },
    ],
  },
});

const StartRectNodeDefault = (updateSelectedState) => {
  const nodeDefault = RectNodeDefault();
  return {
    ...nodeDefault,
    data: { type: EventItemType.StartEvent, desc: EventItemType.getDesc(EventItemType.StartEvent) },
    component: <ReactNode updateSelectedState={updateSelectedState} />,
  };
};

const EndRectNodeDefault = (updateSelectedState) => {
  const nodeDefault = RectNodeDefault();
  return {
    ...nodeDefault,
    data: { type: EventItemType.EndEvent, desc: EventItemType.getDesc(EventItemType.EndEvent) },
    component: <ReactNode updateSelectedState={updateSelectedState} />,
  };
};

const WorkRectNodeDefault = (updateSelectedState) => {
  const nodeDefault = RectNodeDefault();
  return {
    ...nodeDefault,
    data: { type: EventItemType.WorkTask, desc: EventItemType.getDesc(EventItemType.WorkTask) },
    component: <ReactNode updateSelectedState={updateSelectedState} />,
  };
};

const VerifyRectNodeDefault = (updateSelectedState) => {
  const nodeDefault = RectNodeDefault();
  return {
    ...nodeDefault,
    data: { type: EventItemType.VerifyTask, desc: EventItemType.getDesc(EventItemType.VerifyTask) },
    component: <ReactNode updateSelectedState={updateSelectedState} />,
  };
};

export function newGrapNodeMeta({ x, y, itemType, updateSelectedState }) {
  let data;
  if (itemType === EventItemType.StartEvent) {
    // data = StartRectDefault();
    data = StartRectNodeDefault(updateSelectedState);
  } else if (itemType === EventItemType.EndEvent) {
    // data = EndRectDefault();
    data = EndRectNodeDefault(updateSelectedState);
  } else if (itemType === EventItemType.VerifyTask) {
    // data = VerifyRectDefault();
    data = VerifyRectNodeDefault(updateSelectedState);
  } else if (itemType === EventItemType.WorkTask) {
    // data = WorkRectDefault();
    data = WorkRectNodeDefault(updateSelectedState);
  }
  return { ...data, x, y };
}

// 导出的JSON格式包含了已定义的图元的属性，需要在导出的时候删除
export function optimizeJSON(graphJson) {
  let result = _.cloneDeep(graphJson);
  if (result.cells) {
    result.cells.forEach((item) => {
      // delete item['size'];
      // delete item['ports'];
      // delete item['data'];
      delete item['component'];
      if (item.data && item.data.selected) {
        delete item.data['selected'];
      }
    });
  }
  return result;
}

// Graph option
export const graphOptions = {
  // container,
  // width: wrapper.clientWidth,
  // height: wrapper.clientHeight,
  background: {
    color: '#E6EAF2FF',
  },
  grid: true,
  connecting: {
    router: 'manhattan',
    connector: {
      name: 'rounded',
      args: {
        radius: 8,
      },
    },
    snap: {
      radius: 20,
    },
    allowBlank: false,
    allowMulti: 'withPort',
    allowLoop: false,
    allowEdge: false,
    allowNode: false,
    allowPort: true,
    anchor: 'center',
    connectionPoint: 'anchor',
    createEdge() {
      return new Shape.Edge({
        id: randomId(),
        attrs: {
          line: {
            stroke: '#888',
            strokeWidth: 2,
            targetMarker: {
              name: 'block',
              width: 12,
              height: 8,
            },
          },
        },
        zIndex: 1,
      });
    },
    validateConnection({ targetMagnet }) {
      return !!targetMagnet;
    },
  },
  highlighting: {
    magnetAdsorbed: {
      name: 'stroke',
      args: {
        attrs: {
          fill: '#5F95FF',
          stroke: '#5F95FF',
        },
      },
    },
    magnetAvailable: {
      name: 'stroke',
      args: {
        padding: 4,
        attrs: {
          'stroke-width': 2,
          stroke: 'red',
        },
      },
    },
  },
  // resizing: true,
  // rotating: true,
  // 鼠标滚轮
  // mousewheel: {
  //   enabled: true,
  //   zoomAtMousePosition: true,
  //   modifiers: 'ctrl',
  //   minScale: 0.5,
  //   maxScale: 3,
  // },
  // 点选/框选
  selecting: {
    enabled: false,
    multiple: false,
    showNodeSelectionBox: false,
  },
  // 画布滚动
  scroller: {
    enabled: true,
    pageVisible: false,
    pageWidth: 800,
    pageHeight: 600,
    autoResize: true,
    // pageBreak: true,
    pannable: true,
  },
  snapline: true,
  keyboard: true,
  clipboard: true,
};

// 根据不同 shapeType 将 props 写入到图元绘制节点中去
// shapeType 图元的类型
// props 从 model 中提取的 自定义 props
// node 图元的图结构
export function propsToNode(shapeType, props, node) {
  switch (shapeType) {
    case 'start-rect':
      node.setPropByPath('props/name', props.name || '');
      node.setPropByPath('props/desc', props.desc || '');
      node.setPropByPath('props/pageId', props.pageId || '');
      node.setPropByPath('props/pageUrl', props.pageUrl || '');
      node.setPropByPath('props/actionCommit', props.actionCommit || true);
      node.setPropByPath('props/actionStash', props.actionStash || true);
      node.setPropByPath('props/actionCommitPrint', props.actionCommitPrint || false);
      node.setPropByPath('props/actionEnd', props.actionEnd || false);
      break;
    case 'work-rect':
      node.setPropByPath('props/name', props.name || '');
      node.setPropByPath('props/desc', props.desc || '');
      node.setPropByPath('props/pageId', props.pageId || '');
      node.setPropByPath('props/pageUrl', props.pageUrl || '');
      node.setPropByPath('props/actionCommit', props.actionCommit || true);
      node.setPropByPath('props/actionStash', props.actionStash || true);
      node.setPropByPath('props/actionCommitPrint', props.actionCommitPrint || false);
      node.setPropByPath('props/actionEnd', props.actionEnd || false);
      node.setPropByPath('props/nodeUsers', props.nodeUsers || []);
      break;
    case 'verify-diamond':
      node.setPropByPath('props/name', props.name || '');
      node.setPropByPath('props/desc', props.desc || '');
      node.setPropByPath('props/pageId', props.pageId || '');
      node.setPropByPath('props/pageUrl', props.pageUrl || '');
      node.setPropByPath('props/actionAgree', props.actionAgree || true);
      node.setPropByPath('props/actionReject', props.actionReject || true);
      node.setPropByPath('props/actionForward', props.actionForward || true);
      node.setPropByPath('props/actionReturnback', props.actionReturnback || true);
      node.setPropByPath('props/actionEnd', props.actionEnd || false);
      node.setPropByPath('props/nodeUsers', props.nodeUsers || []);
      break;
    case 'edge':
      // node.setPropByPath('props/name', props.name || '');
      // node.setPropByPath('props/desc', props.desc || '');
      node.setPropByPath('props/dataFlowCondition', props.dataFlowCondition || 'custom');
      node.setPropByPath('props/conditionRelation', props.conditionRelation || 'any');
      node.setPropByPath('props/conditionList', props.conditionList || []);
      break;
    default:
      break;
  }
}

const StartRectDefault = () => ({
  shape: START_RECT_NAME,
  id: randomId(),
  x: 40,
  y: 40,
  props: {
    name: '开始',
    desc: '',
    pageId: '',
    pageUrl: '',
    actionCommit: true,
    actionStash: true,
    actionCommitPrint: false,
    actionEnd: false,
  },
});

const WorkRectDefault = () => ({
  shape: WORK_RECT_NAME,
  id: randomId(),
  x: 40,
  y: 40,
  props: {
    name: '流程节点',
    desc: '',
    pageId: '',
    pageUrl: '',
    actionCommit: true,
    actionStash: true,
    actionCommitPrint: false,
    actionEnd: false,
    nodeUsers: [],
  },
});

// const VerifyDiamondDefault = () => ({
//   shape: VERIFY_DIAMOND_NAME,
//   id: randomId(),
//   x: 40,
//   y: 40,
//   props: {
//     name: '审批节点',
//     desc: '',
//     pageId: '',
//     pageUrl: '',
//     actionAgree: true,
//     actionReject: true,
//     actionForward: true,
//     actionReturnback: true,
//     actionEnd: false,
//     nodeUsers: [],
//   },
// });

const VerifyRectDefault = () => ({
  shape: VERIFY_RECT_NAME,
  id: randomId(),
  x: 40,
  y: 40,
  props: {
    name: '审批任务',
    desc: '',
    pageId: '',
    pageUrl: '',
    actionAgree: true,
    actionReject: true,
    actionForward: true,
    actionReturnback: true,
    actionEnd: false,
    nodeUsers: [],
  },
});

// const EndCircleDefault = () => ({
//   shape: END_CIRCLE_NAME,
//   id: randomId(),
//   x: 40,
//   y: 40,
//   props: {
//     name: '结束',
//     desc: '',
//   },
// });

const EndRectDefault = () => ({
  shape: END_RECT_NAME,
  id: randomId(),
  x: 40,
  y: 40,
  props: {
    name: '结束',
    desc: '',
  },
});
